﻿using MXERP.Shared.Wrapper;

namespace MXERP.Shared.Extensions
{
    public static class ListExtension
    {
        /// <summary>
        /// 将列表转换为树形结构
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="list">数据</param>
        /// <returns></returns>
        public static List<T>? ToTree<T>(this List<T>? list) where T: ITreeResponse<T>
        {
            //空树
            if (list == null || list.Count == 0)
            {
                return null;
            }
            var items = new List<T>(list.FindAll(item => true));
            var treelist = new List<T>();
            var map = new Dictionary<long, T>();
            foreach (var item in items)
            {
                map.Add(item.Id, item);
            }
            foreach (var value in map.Values)
            {
                if (value.PId == null)
                {
                    treelist.Add(value);
                }
                else
                {
                    var obj = map[value.PId.Value];
                    if (obj.Children == null)
                    {
                        obj.Children = new List<T>();
                    }
                    obj.Children.Add(value);
                }
            }
            return treelist;
        }
    }
}
